package edu.sandau.b230111.b23011125.Controller;

import edu.sandau.b230111.b23011125.Global.ContestWithProblems;
import edu.sandau.b230111.b23011125.Global.GlobalDefine;
import edu.sandau.b230111.b23011125.Global.RankListWithUser;
import edu.sandau.b230111.b23011125.Model.Contest;
import edu.sandau.b230111.b23011125.Model.Problem;
import edu.sandau.b230111.b23011125.Model.RankList;
import edu.sandau.b230111.b23011125.Service.ContestService;
import edu.sandau.b230111.b23011125.Service.ProblemService;
import edu.sandau.b230111.b23011125.Service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
public class ContestController {
    @Autowired
    private ContestService contestService;
    @Autowired
    private ProblemService problemService;
    @Autowired
    private UserService userService;

    @RequestMapping("/contest/list")
    public String listAllContest(ModelMap map, HttpServletRequest request, @RequestParam(value = "page",defaultValue = "0") String pageCnt){
        String loggedUserid = (String)request.getSession().getAttribute("userid");
        if(null==loggedUserid){//未登录
            return "redirect:/login";
        }
        Page<Contest> contests = contestService.queryAllContest(Integer.parseInt(pageCnt), GlobalDefine.PAGESIZE);
        map.put("totalElement",contests.getTotalElements());
        map.put("totalPage",contests.getTotalPages());
        map.put("nowPage",contests.getNumber());
        List<Contest> contestList = contests.getContent();
        map.put("contests",contestList);
        String isAdmin = (String)request.getSession().getAttribute("isAdmin");
        if(isAdmin==null){
            map.put("isAdmin","NO");
        }
        else{
            map.put("isAdmin","YES");
        }
        return "contest_list";
    }

    @RequestMapping("/contest/{contestid}")
    public String getContestDetails(HttpServletRequest request, ModelMap map, @PathVariable("contestid") String contestid){
        String loggedUserid = (String)request.getSession().getAttribute("userid");
        if(null==loggedUserid){//未登录
            return "redirect:/login";
        }
        Contest contest = contestService.queryContestById(contestid);
        if(contest==null){ //题号不存在
            return "notfound";
        }

        ContestWithProblems contestWithProblems =  contestService.queryContestWithProblems(contestid);
        map.put("contest",contestWithProblems);
        map.put("endtime",contest.getEndtime().toString());
        return "contest";
    }


    @RequestMapping("/contest/{contestid}/problem/{problemid}")
    public String problemDetails(HttpServletRequest request,ModelMap map,@PathVariable("problemid") String problemid,@PathVariable("contestid") String contestid){
        String loggedUserid = (String)request.getSession().getAttribute("userid");
        if(null==loggedUserid){//未登录
            return "redirect:/login";
        }
        Problem problem = problemService.queryProblemById(problemid);
        if(problem==null){ //题号不存在
            return "notfound";
        }

        map.put("problem",problem);
        boolean iscontest = true;
        map.put("iscontest",iscontest);

        map.put("contest",contestService.queryContestById(contestid));

        return "problem";
    }

    @RequestMapping("/api/contest/{contestid}/problem/{count}/submit")
    public String contestSubmit(HttpServletRequest request, HttpServletResponse response, ModelMap map, @PathVariable("contestid") String contestid, @PathVariable("count") String count) throws IOException {
        String loggedUserid = (String)request.getSession().getAttribute("userid");
        if(null==loggedUserid){//未登录
            return "redirect:/login";
        }
        Random random = new Random();
        String result = "等待中";
        int randomresult = (random.nextInt(4))+1;
        if(randomresult==1) {
            result = "编译错误";
        }
        else if(randomresult==2){
            result = "答案错误";
        }
        else if(randomresult==3){
            result = "运行超时";
        }
        else{
            result = "通过";
        }
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        contestService.modifyRanklist(contestid,loggedUserid,result,count);
        out.print("<script language=\"javascript\">alert('"+result+"');window.location.href='/contest/"+contestid+"/ranklist'</script>");
        return "waitpage";
    }


    @RequestMapping("/contest/{contestid}/ranklist")
    public String getRankList(HttpServletRequest request, HttpServletResponse response, ModelMap map, @PathVariable("contestid") String contestid,@RequestParam(value = "page",defaultValue = "0" ) String pageCnt){
        String loggedUserid = (String)request.getSession().getAttribute("userid");
        if(null==loggedUserid){//未登录
            return "redirect:/login";
        }
        Page<RankList> ranklists =  contestService.queryAllRankList(contestid,Integer.parseInt(pageCnt),GlobalDefine.PAGESIZE);
        map.put("totalElement",ranklists.getTotalElements());
        map.put("totalPage",ranklists.getTotalPages());
        map.put("nowPage",ranklists.getNumber());
        List<RankList> rankLists = ranklists.getContent();
        List<RankListWithUser> rankListWithUsers = new ArrayList<>();
        for(RankList x : rankLists){
            RankListWithUser y = new RankListWithUser(x,userService.queryUserInfoByUserId(x.getUserid()).getName());
            rankListWithUsers.add(y);
        }
        Contest contest = contestService.queryContestById(contestid);
        map.put("ranklists",rankListWithUsers);
        map.put("contest",contest);
        return "ranklist";
    }
}
